<template>

	<uni-search-bar @confirm="toSearch" placeholder="请输入查找的公交或地铁线路" v-model="searchKey" @input="" />
	<swiper style="height: 200px;" :indicator-dots="true" :autoplay="true" :interval="3000" :duration="1000">
		<swiper-item v-for="(item,index) in rotateList" :key="index">
			<view class="swiper-item">
				<image :src="item.url" style="width: 100%;" mode=""></image>
			</view>
		</swiper-item>
	</swiper>
	<!-- 当前位置 -->
	<view class="location-widget">
		<text>当前所处位置：{{ currentAddress }}</text>
		<text>经度：{{ currentPos.longitude  }}</text>
		<text>纬度：{{ currentPos.latitude}}</text>
	</view>
	<view class="icon-grid" style="height: 80px;">
		<view v-for="(item, index) in icons" :key="index" class="icon-item" @click="handleIconClick(item)">
			<image :src="item.src" :alt="item.alt" style="width: 25%; height: 60%;" mode="aspectFill"></image>
			<text>{{ item.text }}</text>
		</view>
	</view>

	<div id="container" style="width: 100%; height: 200px;"></div>
	<!-- 天气 -->
	<view class="weather"
		style="height: 100rpx; border: 1px solid #ccc; margin: 5px; border-radius: 5px; display: flex; justify-content: space-between; padding: 10rpx; align-items: center;">
		<view class="icon" style="width: 100rpx; height: 100rpx;">
			<image style="width: 100%; height: 100%;" :src="'/static/Weather/icon/' + weatherNow.value.icon + '.png'"
				mode="aspectFill"></image>
		</view>
		<view class="text" style="font-size: 50rpx; margin-left: 10px;">
			{{ weatherNow.value.temp }}°C
		</view>
		<view class="text" style="font-size: 34rpx; margin-left: 10rpx;">
			{{ weatherNow.value.text }}
		</view>
		<view class="text" style="margin-left: 10rpx;">
			{{ weatherNow.value.windDir }} {{ weatherNow.value.windScale }}级
		</view>
		<view>
			<view class="text" style="margin-left: 10px;">
				体感温度： {{ weatherNow.value.feelsLike }}°C
			</view>
			<view class="text" style="margin-left: 10px;">
				湿度： {{ weatherNow.value.humidity }}%
			</view>
		</view>
	</view>
</template>

<script setup>
	import {
		onMounted,
		ref
	} from 'vue'
	import axios from 'axios'; // 引入axios库
	import {
		onLoad
	} from '@dcloudio/uni-app'
	import {
		CONFIG
	} from '../../utils/config'
	import {
		userStore
	} from '../../store/userStore'
	const store = userStore()

	const weatherNow = ref({});
	const currentPos = ref({
		latitude: 0,
		longitude: 0
	}); // 提供初始值
	const currentAddress = ref(''); // 提供初始值
	async function getWeather() {
		try {
			let res = await axios.get(CONFIG.hefeng_key, {
				params: {
					key: CONFIG.hefeng_key,
					location: CONFIG.hefeng_location
				}
			});
			if (res.Code == 200) {
				weatherNow.value = res.data.data.now;
				console.log(weatherNow.value);
			}
		} catch (error) {
			console.error('获取天气信息失败', error);
		}
	}

	onMounted(() => {
		getWeather();
	});
	const searchKey = ref("")
	onLoad(() => {
		getCureentPos()
		getRotatePic()
		// getWeather();
	})
	const icons = ref([{
			src: '/static/icons/ditu.png',
			alt: '地图',
			text: '地图',
			url: 'https://www.amap.com/dir?from%5Bname%5D=%E6%88%91%E7%9A%84%E4%BD%8D%E7%BD%AE'
		},
		{
			src: '/static/icons/jiudian.png', // 酒店民宿图标路径
			alt: '酒店',
			text: '酒店',
			url: 'https://ditu.amap.com/search?query=%E9%85%92%E5%BA%97&city=610100&geoobj=108.939289%7C34.323584%7C108.944439%7C34.328262&_src=around&zoom=17'
		},
		{
			src: '/static/icons/douyin.png', // 休闲玩乐图标路径
			alt: '抖音',
			text: '抖音',
			url: 'https://www.douyin.com/?recommend=1'

		},
		// {
		// 	src: '/static/icons/bilibili.png', // 休闲玩乐图标路径
		// 	alt: 'bilibili',
		// 	text: 'bilibili',
		// 	url: 'https://www.bilibili.com/'

		// },
		{
			src: '/static/icons/xinwen.png',
			alt: '新闻',
			text: '新闻',
			url: 'https://m.chinanews.com/'
		},
		// https://m.chinanews.com/
		// https://www.xiancn.com/node_16181.html
		{
			src: '/static/icons/meishi.png', // 美食图标路径
			alt: '美食',
			text: '美食',
			url: 'https://ditu.amap.com/search?query=%E7%BE%8E%E9%A3%9F'

		},
		{
			src: '/static/icons/dache.png', // 打车图标路径
			alt: '打车',
			text: '打车',
			url: 'https://common.diditaxi.com.cn/general/webEntry?h=1#/'
		}, {
			src: '/static/icons/tianqi.png', // 打车图标路径
			alt: '天气',
			text: '天气',
			url: 'https://www.weather.com.cn/weather/101110101.shtml'
		},

		{
			src: '/static/icons/dianying.png', // 电影演出图标路径
			alt: '电影',
			text: '电影',
			url: 'https://www.maoyan.com/',
		}
	]);
// https://m.maoyan.com/ajax/detailmovie?movieId=2
	

	function toSearch() {
		if (searchKey.value == "") {
			uni.showToast({
				title: "请输入查找的公交或地铁线路",
				icon: 'none'
			})
		} else {
			window.location.href = `https://uri.amap.com/line?name=${searchKey.value}&city=029&callnative=0`
		}
	}


	// const searchList = ref("")
	const rotateList = ref([])
	async function getRotatePic() {
		try {
			let res = await uni.$get(CONFIG.leanCloud_url + "/1.1/classes/RotatePic");
			if (res.statusCode == 200) {
				rotateList.value = res.data.results;
			}
		} catch (error) {
			console.error('获取轮播图数据失败', error);
			uni.showToast({
				title: '获取轮播图数据失败',
				icon: 'none'
			});
		}
		console.log(rotateList.value);
	}
	// 获取经纬度
	function getCureentPos() {
		uni.getLocation({
			type: 'wgs84',
			success: function(res) {
				console.log('当前位置的经度：' + res.longitude + ', 纬度：' + res.latitude);
				currentPos.value = {
					latitude: res.latitude,
					longitude: res.longitude
				};
				getReverseGeocoding(res.latitude, res.longitude); // 获取地址
			},
			fail: function(error) {
				console.error('获取位置失败', error);
				uni.showToast({
					title: "获取位置失败: " + error.message,
					icon: 'none'
				});
			}
		});
	}

	function getReverseGeocoding(latitude, longitude) {
		axios.get(`https://restapi.amap.com/v3/geocode/regeo?key=${CONFIG.amap_key}&location=${latitude},${longitude}`)
			.then(response => {
				const address = response.data.regeocodeData.addressComponent.province +
					response.data.regeocodeData.addressComponent.city +
					response.data.regeocodeData.addressComponent.district +
					response.data.regeocodeData.addressComponent.streetNumber.street;
				currentAddress.value = address; // 更新当前地址
			})
			.catch(error => {
				// console.error('地理编码失败', error);
				uni.showToast({
					title: "地理编码服务失败: " + error.message,
					icon: 'none'
				});
			});
	}

	onMounted(() => {
		getCureentPos(); // 组件挂载时获取位置
	});
	// function handleIconClick(text) {
	// 	const baseURL = "https://m.amap.com/search?query=";
	// 	const encodedText = encodeURIComponent(text);
	// 	const url = baseURL + encodedText;

	// 	// 使用window.open打开新窗口
	// 	window.open(url, '_blank');
	// }
	function handleIconClick(item) {
		if (item.url) {
			window.open(item.url, '_blank');
		} else {
			// 默认行为，比如显示一个提示
			uni.showToast({
				title: "此图标无链接",
				icon: 'none'
			});
		}
	}

	const map = ref(null);
	onMounted(() => {
		// 初始化地图
		map.value = new AMap.Map('container', {
			zoom: 10, // 初始地图级别
			center: [108.938367, 34.323885] // 初始地图中心点（这里以北京为例）
		});

		// 获取当前位置
		const geolocation = new AMap.Geolocation({
			enableHighAccuracy: true, // 是否使用高精度定位，默认:true
			timeout: 10000, // 超过10秒后停止定位，默认：5s
			buttonPosition: 'RB', // 定位按钮的停靠位置
			buttonOffset: new AMap.Pixel(10, 20), // 定位按钮距离对应角落的距离
			zoomToAccuracy: true // 定位成功后是否自动调整地图视野到定位点
		});

		map.value.addControl(geolocation);
		geolocation.getCurrentPosition().then(function(status, result) {
			if (status === 'complete') {
				const longitude = result.position.getLng();
				const latitude = result.position.getLat();
				console.log(`当前位置的经度：${longitude}, 纬度：${latitude}`);
				// 更新地图中心点到当前位置
				map.value.setCenter([longitude, latitude]);
			} else {
				console.error('定位失败');
			}
		});
	});
</script>


<style lang="scss" scoped>
	.icon-grid {
		display: grid;
		grid-template-columns: repeat(4, 1fr);
		/* 每行4个图标 */
		gap: 10px;
		/* 图标之间的间隔 */
		padding: 10px;
		/* 容器内边距 */
	}

	.icon-item {
		display: flex;
		flex-direction: column;
		align-items: center;
		text-align: center;
		/* 确保文字居中 */
	}

	.icon-item image {
		width: 50px;
		/* 图标宽度 */
		height: 50px;
		/* 图标高度 */
		margin-bottom: 5px;
		/* 图标与文字之间的间隔 */
	}

	.icon-item text {
		font-size: 10px;
		/* 文本大小 */
		color: #333;
		/* 文本颜色 */
	}

	// 地图
	#container {
		width: 100%;
		height: 200px;
	}
</style>